<script setup lang="ts">
import type { ID } from '#/api/common';
import type { EmailTemplateVO } from '#/api/config/template/email/model';
import type { OssFile } from '#/api/system/oss/model';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message, Skeleton } from 'ant-design-vue';

import { emailTemplateInfo } from '#/api/config/template/email';
import { ossInfo } from '#/api/system/oss';

const loading = ref(false);
const templateUrl = ref<any>('');
const defaultTitle = '邮件模板预览';
const defaultDesc = '';
const title = ref(defaultTitle);
const description = ref(defaultDesc);
const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: true,
  showConfirmButton: false,
  cancelText: '关闭',
  onClosed: handleClosed,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id, ossId } = modalApi.getData() as { id?: ID; ossId?: ID };
    loading.value = true;
    let iframeUrl = '';
    if (id) {
      iframeUrl = (await getEmailTemplateUrlById(id)) ?? '';
    } else if (ossId) {
      iframeUrl = (await getEmailTemplateUrlByOssId(ossId)) ?? '';
    }
    templateUrl.value = iframeUrl.replace('http://', 'https://');
    loading.value = false;
    modalApi.modalLoading(false);
    if (!templateUrl.value) {
      message.warning('查无模板文件');
      modalApi.close();
    }
  },
});

function handleClosed() {
  templateUrl.value = '';
  title.value = defaultTitle;
  description.value = defaultDesc;
}

async function getEmailTemplateUrlByOssId(emailOssId: ID) {
  const resp: OssFile[] = await ossInfo([emailOssId]);
  return resp && resp.length > 0 ? (resp[0] as OssFile).url : null;
}

async function getEmailTemplateUrlById(id: ID) {
  const emailTemplate: EmailTemplateVO = await emailTemplateInfo(id);
  title.value = `邮件模板预览：${emailTemplate.emailName}`;
  description.value = emailTemplate.emailSubject;
  const resp: OssFile[] = await ossInfo([emailTemplate.emailOssId]);
  return resp && resp.length > 0 ? (resp[0] as OssFile).url : null;
}
</script>

<template>
  <BasicModal :title="title" :description="description" class="w-[80%]">
    <!--<div class="flex min-h-[600px]">-->
    <iframe
      :src="templateUrl"
      class="h-full min-h-[600px] w-full border"
    ></iframe>
    <!--    </div>-->
    <Skeleton v-if="loading" active />
  </BasicModal>
</template>
